package com.metagurukul.metagranth.actionservlets;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.metagurukul.metagranth.service.TagService;
import com.metagurukul.metagranth.vo.Tag;

/**
 *  Servlet implementation class GetTagListServlet
 *  This servlet holds the functionality of getting the names ofd all the tags added so far 
 *  on any questions on the site.
 *  It also count the number of tags of each tag added so far.
 *  
 *  
 * @author team MetaGranth
 *
 */
public class GetTagListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetTagListServlet() {
		super();
	
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * this function will get the names of all the tags added so far for the questions asked so far on site
	 * by calling getTagsList() function on the TagService Service layer.
	 * It will also count the number of each tag added so far by calling getTagCount() function on the TagService service layer.
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doPerform(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		if(session.getAttribute("userId")!=null){
		try {
			//get tagList details by calling getTagsList() function
			ArrayList<Tag> tagsList = TagService.getTagsList();
			//tagCounts is used to hold the count on number of tags
			ArrayList<Integer> tagCounts = new ArrayList<Integer>();
			for (Tag tag : tagsList) {
				//getTagCount gets the total number of tags associated
				int count = TagService.getTagCount(tag);
				tagCounts.add(count);
			}
			request.setAttribute("tagCounts", tagCounts);
			request.setAttribute("tagsList", tagsList);
			request.getRequestDispatcher("tags.jsp").forward(request, response);
		} catch (Exception exception) {
			request.setAttribute("errormsg", exception.getMessage());
			request.getRequestDispatcher("errorPage.jsp").forward(request,
					response);
		}
		}else {
			response.sendRedirect("index.jsp");
		}
	}

}
